
// Copyright (C) Recursion Company. All rights reserved.

#include "stdafx.h"
#include "vol_user_app_info.h"
#include "zlib\zlib.h"

CVolMem& VolCompress (const BYTE* pbData, INT nDataSize, CVolMem& memResult)
{
    memResult.Empty ();

    if (nDataSize > 0)
    {
	    INT nOutSize = nDataSize + nDataSize / 1000 + 1024;
	    LPBYTE pOut = (LPBYTE)memResult.Alloc (sizeof (DWORD) * 2 + nOutSize);

	    *(LPDWORD)pOut = MY_ZIPFILE_MARK;
	    *(LPDWORD)(pOut + sizeof (DWORD)) = (DWORD)nDataSize;
	    if (nDataSize == 0)
	    {
		    nOutSize = sizeof (DWORD) * 2;
	    }
	    else if (compress (pOut + sizeof (DWORD) * 2, (ULONG*)&nOutSize, pbData, nDataSize) == Z_OK)
	    {
		    nOutSize += sizeof (DWORD) * 2;
	    }
	    else
		    nOutSize = 0;

        memResult.Realloc (nOutSize);
    }

    return memResult;
}

CVolMem& VolUncompress (const BYTE* pbData, INT nDataSize, CVolMem& memResult)
{
    memResult.Empty ();

	if (nDataSize >= sizeof (DWORD) * 2 && *(LPDWORD)pbData == MY_ZIPFILE_MARK)
	{
		INT nOutSize = *(LPINT)(pbData + sizeof (DWORD));

		if (nOutSize > 0)
		{
		    nOutSize = nOutSize * 2;

			if (uncompress ((LPBYTE)memResult.Alloc (nOutSize), (ULONG*)&nOutSize,
					pbData + sizeof (DWORD) * 2, nDataSize - sizeof (DWORD) * 2) != Z_OK)
            {
				nOutSize = 0;
            }

            memResult.Realloc (nOutSize);
		}
	}

    return memResult;
}
